import { changePasswordWithoutOld } from '../../utils/user-api';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    newPassword: '',
    confirmPassword: '',
    
    // 验证状态
    newPasswordError: '',
    confirmPasswordError: '',
    newPasswordStatus: '',
    confirmPasswordStatus: '',
    newPasswordTips: '密码长度6-20位，建议包含字母和数字',
    confirmPasswordTips: '',
    
    canSubmit: false,
    isSubmitting: false
  },

  onLoad(options) {
    // 检查是否从默认密码提醒跳转过来
    if (options.fromDefault) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '为了账户安全，请修改默认密码',
        theme: 'warning',
        duration: 3000
      });
    }
  },
  onBack() {
    wx.navigateBack({
      delta: 1, // 返回上一级页面
    })
  },

  // 新密码输入
  onNewPasswordChange(e) {
    this.setData({
      newPassword: e.detail.value
    });
    this.validateForm();
  },

  onNewPasswordBlur() {
    this.validateNewPassword();
  },

  // 确认密码输入
  onConfirmPasswordChange(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
    this.validateForm();
  },

  onConfirmPasswordBlur() {
    this.validateConfirmPassword();
  },

  // 验证新密码
  validateNewPassword() {
    const { newPassword } = this.data;
    
    if (!newPassword) {
      this.setData({
        newPasswordError: '请输入新密码',
        newPasswordStatus: 'error'
      });
      return false;
    }
    
    if (newPassword.length < 6 || newPassword.length > 20) {
      this.setData({
        newPasswordError: '密码长度应为6-20位',
        newPasswordStatus: 'error'
      });
      return false;
    }
    
    // 简单的密码强度检查
    const hasLetter = /[a-zA-Z]/.test(newPassword);
    const hasNumber = /\d/.test(newPassword);
    
    if (!hasLetter || !hasNumber) {
      this.setData({
        newPasswordError: '密码应包含字母和数字',
        newPasswordStatus: 'warning'
      });
      return false;
    }
    
    this.setData({
      newPasswordError: '',
      newPasswordStatus: 'success'
    });
    return true;
  },

  // 验证确认密码
  validateConfirmPassword() {
    const { newPassword, confirmPassword } = this.data;
    
    if (!confirmPassword) {
      this.setData({
        confirmPasswordError: '请确认新密码',
        confirmPasswordStatus: 'error'
      });
      return false;
    }
    
    if (confirmPassword !== newPassword) {
      this.setData({
        confirmPasswordError: '两次输入的密码不一致',
        confirmPasswordStatus: 'error'
      });
      return false;
    }
    
    this.setData({
      confirmPasswordError: '',
      confirmPasswordStatus: 'success'
    });
    return true;
  },

  // 验证表单
  validateForm() {
    const { newPassword, confirmPassword } = this.data;
    const canSubmit = newPassword && confirmPassword && 
                     newPassword.length >= 6 && 
                     newPassword === confirmPassword;
    
    this.setData({ canSubmit });
  },

  // 提交修改
  async onSubmit() {
    if (!this.data.canSubmit || this.data.isSubmitting) {
      return;
    }

    // 最终验证
    if (!this.validateNewPassword() || !this.validateConfirmPassword()) {
      return;
    }

    this.setData({ isSubmitting: true });

    try {
      const { newPassword } = this.data;
      
      const result = await changePasswordWithoutOld(newPassword);
      
      if (result.success) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '密码修改成功',
          theme: 'success',
          duration: 2000
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
        
        // 更新本地用户信息（移除默认密码标记）
        const userInfo = wx.getStorageSync('user_info');
        if (userInfo) {
          userInfo.hasDefaultPassword = false;
          wx.setStorageSync('user_info', userInfo);
        }
        
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.message || '密码修改失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '网络错误，请重试',
        theme: 'error'
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  }
}); 